﻿$(function () {
    var cardViewThreshold = 580;
    /* Set a locale manually */
    //$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['en-US']);
    loaddata();
    /* Auto adjust the table's view type (table/card) when screen size changes */
    //window.onresize = function () {
    //    $('#table').bootstrapTable('refreshOptions', {
    //        cardView: document.body.clientWidth < cardViewThreshold
    //    });
    //};
});
function reloaddata() {
    //var opt = {
    //    url: "/lxoa/listvacation/"
    //};
    //$('#table').bootstrapTable('refresh', opt);

    $.ajax({
        url: '/lxoa/expensestatisticslist/',
        type: 'get',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },
        success: function (data) {
            //if (data && data.total > 0) {
                $("#table").bootstrapTable('load', data.rows);
            //} else {
            //    //alert('error');
            //}
        }
    })  
}

function loaddata() {
    $.ajax({
        url: '/lxoa/expensestatisticslist/',
        type: 'get',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },        
        success: function (data) {
            //if (data && data.total>0) {
                binddata(data.rows);
                //$('.columns-right').append('<button class="btn btn-primary" type="button" data-toggle="modal" data-target="#myModal" name="toggle" aria-label="toggle" title=""> 申请 </button>&nbsp;<button class="btn btn-primary" style="margin-left:4px;" type="button" onclick="vacationtj()" name="toggle" aria-label="toggle" title=""> 统计 </button>');
                $('.columns-right').append('<button class="btn btn-primary" type="button" data-toggle="modal" data-target="#myModal" name="toggle" aria-label="toggle" title=""> 统计 </button>');
                $('.keep-open').hide();
                var uname = $('#usernamespan').html();
                //$("#vac_person").empty().append("<option value='" + uname + "' mail=''>" + uname + "</option>").attr("disabled", "disabled");
                //getuserlist();//order last one load it.

                //alert('success');
            //} else {
            //    //alert('error');
            //}
        }
    })
}

function binddata(datas) {
    var cardViewThreshold = 580;
    $('#table').bootstrapTable({
        cardView: document.body.clientWidth < cardViewThreshold,
        //striped: true,
        search: true,
        pagination: true,
        ageNumber: 1,
        pageSize: 10,
        pageList: [10, 20, 30, 50],
        showColumns: true,
        showToggle: false,
        //showExport: false,
        columns: [{
            title: '序号',
            field: '',
            formatter: function (value, row, index) {
                return index + 1;
            }
        },{
            field: 'applyuser',
            title: '申请人',
            sortable: true
        },{
            field: 'title',
            title: '报销类型',
            sortable: true
        }, 
        {
            field: 'applydate',
            title: '申请日期',
            sortable: true
            },
            {
                field: 'approvaldate',
                title: '审批日期',
                sortable: true
            },
        {
            field: 'totalprice',
            title: '金额',
            sortable: true
        },
        {
            field: 'remark',
            title: '备注',
            sortable: true
        },
        {
            field: 'approvaluser',
            title: '审批人',
            sortable: true,
            formatter: Formatterstatus
        }],
        data: datas
    });
}
function Formatterstatus(value, row, index) {
    return [value.split('$')[0]].join("");
}
function Formatteropration(value, row, index) {
    if (row && row.approvalstatus && row.approvalstatus == '1') {
        return [''].join("");
    } else {
        return ['<button class="btn btn-primary" type="button" onclick="addrow()" name="toggle" title="审批">审批</button>'].join("");
    }
}
function getuserlist() {
    $.ajax({
        url: '/lxoa/getuserlist/',
        type: 'get',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },
        success: function (data) {
            if (data && data.length > 0) {
                $("#vac_person").empty();
                $("#vac_person2").empty();
                for (var i = 0; i < data.length; i++) {
                    $("#vac_person").append("<option value='" + data[i].USER + "' mail='" + data[i].MAIL + "'>" + data[i].USER + "</option>");
                    $("#vac_person2").append("<option value='" + data[i].USER + "' mail='" + data[i].MAIL + "'>" + data[i].USER + "</option>");
                }
                //alert('success');
            } else {
                //alert('error');
            }
        }
    })
}

function delrow(obj) {
    $(obj).parent().parent().remove();
}
function addrow() {
    var str = '<tr data-index="0"><td style=""><select class="selectpicker" name="expense_type" data-style="btn-info"><option value="交通费">交通费</option><option value="住宿费">住宿费</option><option value="其他">其他</option></select></td><td style=""><input type="text" id="" name="txt_price" class="form-control" placeholder="请输入" onkeyup="validatetxt(this)" onblur="validatetxt(this);calctotalprice()" aria-describedby="basic-addon1"></td><td style=""><input type="text" id="" name="txt_description" class="form-control" placeholder="请输入" aria-describedby="basic-addon1"></td><td style=""><button type="button" onclick="delrow(this)" class="close" style="color:red;cursor:pointer;" data-dismiss="modal" aria-hidden="true">×</button></td></tr>';
    $("#expense_items").append(str);
}
function validatetxt(obj) {
    $(obj).val($(obj).val().replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g, ''));
}
function calctotalprice() {
    var item = $("input[name='txt_price']");
    var total = 0;
    for (var i = 0; i < item.length; i++) {
        if ($(item[i]).val().length > 0 && !isNaN($(item[i]).val())) {
            total += parseFloat($(item[i]).val());
        }
    }
    $('#txt_total').val(total);
}

var gyear = $('#vac_year');
var y = new Date().getFullYear();
gyear.empty();
gyear.append("<option value=''>All</option>");
for (var i = 0; i < 5; i++) {
    var c = (y + i) == y ? "selected='selected'" : "";
    gyear.append("<option " + c + " value='" + (y + i) + "'>" + (y + i) + "年</option>");
}

Date.prototype.addDays = function (day, number) {
    var adjustDate = new Date(day + 24 * 60 * 60 * 1000 * 30 * number)
    //alert("Date" + adjustDate.getFullYear() + "-" + adjustDate.getMonth() + "-" + adjustDate.getDate());
    return adjustDate;
}
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds() //??
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

Date.prototype.addDays2 = function (d) {
    this.setDate(this.getDate() + d);
    return this.Format('yyyy-MM-dd');
};
laydate.render({
    elem: '#txt_date',
    lang: 'zh',
    done: function (value, date, endDate) {
        if (value && value.length > 0) {
            $('#vac_date').attr('style', 'border:1px solid #ccc;');
            var curDate = new Date(value);
            $('#vac_enddate').val(curDate.addDays2(parseFloat($('#vac_interval').val())));
        } else {
            $('#vac_enddate').val('');
        }
    }
});

$("#submitbtn").click(function () {
    //if ($('#vac_person').val().length < 1 || $('#vac_person').val() != $('#vac_person2').val()) {
    //    $('#vac_person2').attr('style', 'border:1px solid red;');
    //    return;
    //}
    var vac_dateobj = $('#txt_date');
    if (vac_dateobj && vac_dateobj.val().length > 0) {
        var item = $("input[name='txt_price']");
        var typess = $("select[name='expense_type']");
        var descs = $("input[name='txt_description']");
        var total = 0;
        var count = 0;
        var flag = false;
        for (var i = 0; i < item.length; i++) {
            if ($(item[i]).val().length < 1) {
                if (!flag) {
                    $(item[i]).focus();
                    flag = true;
                }
                count++;
                $(item[i]).attr('style', 'border:1px solid red;');
            }
        }
        if (count>0) {
            return;
        }

        var params = [];
        for (var i = 0; i < item.length; i++) {
            var param = new Object();
            param.types = $(typess[i]).val();
            param.price = $(item[i]).val();
            param.desc = $(descs[i]).val();
            params.push(param);
        }
        var expense_Approver_email = $('#expense_Approver').val();
        var json_obj = {
            applyuser: $('#usernamespan').html(),
            expense_typeb: $('#expense_typeb').val(),
            expense_Approver: $('#expense_Approver').find("option:selected").text(),
            expense_Approver_email:$('#expense_Approver').val(),
            txt_total: $('#txt_total').val(),
            txt_date: $('#txt_date').val(),
            expense_remark: $('#expense_remark').val(),
            datas: params
        }
        var json_str = JSON.stringify(json_obj); 
        $.post("/lxoa/saveexpense/", json_str, function (data) {
            if (data && data.success == '1') {
                $('#myAlert').removeClass('hidden');
                setTimeout(function () {
                        cleartxt();
                        $('#myModal').modal('hide');
                        $('#myAlert').addClass('hidden');
                        reloaddata();
                        //sendmail();
                        //$('#table').bootstrapTable('refresh');
                        //loaddata();
                    }, 1000);
            } else {
                $('#myAlerterror').removeClass('hidden');
                    setTimeout(function () {
                        $('#myAlerterror').addClass('hidden');
                    }, 1500);
            }

        }, "json");

        //$.ajax({
        //    url: '/lxoa/saveexpense/',
        //    type: 'POST',
        //    dataType: 'json',
        //    headers: { "X-CSRFToken": getCookie('csrftoken') },
        //    data: {
        //        expense_typeb: $('#expense_typeb').val(),
        //        expense_Approver: $('#expense_Approver').val(),
        //        txt_total: $('#txt_total').val(),
        //        txt_date: $('#txt_date').val(),
        //        expense_remark: $('#expense_remark').val(),
        //        itmes: "{game_id: 1,level: 'first'},{game_id: 2,level: 'second'}"
        //    },
        //    success: function (data) {
        //        if (data && data.success == '1') {

        //            $('#myAlert').removeClass('hidden');
        //            setTimeout(function () {
        //                $('#myModal').modal('hide');
        //                $('#myAlert').addClass('hidden');
        //                reloaddata();
        //                //sendmail();
        //                //$('#table').bootstrapTable('refresh');
        //                //loaddata();
        //            }, 1000);

        //        } else {
        //            $('#myAlerterror').removeClass('hidden');
        //            setTimeout(function () {
        //                $('#myAlerterror').addClass('hidden');
        //            }, 1500);
        //        }
        //    }
        //})

    } else {
        vac_dateobj.attr('style', 'border:1px solid red;');
        vac_dateobj.focus();
        var item = $("input[name='txt_price']");
        var total = 0;
        var count = 0;
        for (var i = 0; i < item.length; i++) {
            if ($(item[i]).val().length < 1) {
                count++;
                $(item[i]).attr('style', 'border:1px solid red;');
            }
        }
    }
})
function cleartxt() {
      $("input[name='txt_price']").val('');
     $("input[name='txt_description']").val('');
     $('.tr_dynamic').remove();
      $('#txt_total').val('');
      $('#txt_date').val('');
      $('#expense_remark').val('');
}

function sendmail() {
    var vac_date = $('#vac_date').val();
    var vac_person = $('#vac_person').val();
    var vac_interval = $('#vac_interval').val();
    var vac_type = $('#vac_type').val();
    var vac_reason = $('#vac_reason').val();
    var vac_enddate = $('#vac_enddate').val();
    var vac_office = $('#vac_office').val();
    var contents1 = vac_person + ' 请假 ' + vac_interval + " 天,开始时间 " + vac_date + "日 结束时间 " + vac_enddate + "日 ,请假类型 " + vac_type + " office " + vac_office + " 请假原因 " + vac_reason + "。";
    var contents = "<h3>" + vac_person + "请假信息如下：</h3><br/><table border='0' style=''><tr> <td> " + vac_person + " </td><td> 请假" + vac_interval + "天</td></tr><tr><td> 开始时间</td><td> " + vac_date + "日</td></tr><tr><td>结束时间</td><td> " + vac_enddate + "日</td></tr><tr><td>请假类型</td><td> " + vac_type + "</td></tr><tr><td>办公地址</td><td> " + vac_office + "</td></tr><tr><td>请假原因</td><td> " + vac_reason + "</td></tr></table>";
    $.ajax({
        url: '/lxoa/sendmail/',
        type: 'POST',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },
        data: { contenttitle: contents1, content: contents },
        success: function (data) {
            if (data && data.success == '1') {
                //send email success clear text
                $('#vac_date').val('');
                $('#vac_reason').val('');

            } else {
            }
        }
    })
}